/*
 * @Description: webpack的基本配置
 * @Author: Yong
 * @Date: 2021-10-04 09:56:12
 * @LastEditTime: 2021-10-04 20:34:36
 */
const path = require('path')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent') // css模块化处理

const MiniCssExtractPlugin = require('mini-css-extract-plugin')         // 提取css到单独的文件 不放在js - 加快页面加载

const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin')    // 路径优化 - 将tsconfig.json的@路径映射到webpack的路径
// const tsImportPluginFactory = require('ts-import-plugin')               // ts项目集成andtUI组件库 - 按照官网配置 实现按需加载 - 现在改成使用andt-mobile
const optimization = require('./optimization')                          // 提取公共代码webpack.optimization

// 移动端vm适配
const postcssAspectRatioMini = require('postcss-aspect-ratio-mini');
const postcssPxToViewport = require('postcss-px-to-viewport');
const postcssWriteSvg = require('postcss-write-svg');
const postcssCssnext = require('postcss-cssnext');
const postcssViewportUnits = require('postcss-viewport-units');
const cssnano = require('cssnano');

/**
 * @type {import('webpack').Configuration}
 */
module.exports = {
    entry: {
        app: './src/index.tsx',
    },
    output: {
        path: path.resolve(__dirname, '../dist'),
        filename: 'js/[name].[hash].js',
    },
    resolve: {
        extensions: ['.ts', '.tsx', '.js', '.jsx'],
        plugins: [new TsconfigPathsPlugin({ configFile: path.join(__dirname, './../', 'tsconfig.json') })]
        // alias: {
        //     '@': path.join(__dirname, './../src'),
        //     '@scss': path.resolve(__dirname, 'src', 'styles'),
        // }
    },

    plugins: [
        // 加模板文件
        new HtmlWebpackPlugin({
            title: '聊天室',
            template: 'public/index.html',
            filename: 'index.html',
            minify: {
                // 删除注释\空格\删除属性的引号
                removeComments: true,
                collapseWhitespace: true,
                removeAttributeQuotes: true,
            }
        }),
        // 分离CSS
        new MiniCssExtractPlugin({
            filename: 'css/[name].[contenthash:8].css',
        }),
        new CleanWebpackPlugin(),
    ],

    module: {
        rules: [

            { test: /\.(js|jsx)$/, loader: 'babel-loader', exclude: /node_modules/ },
            {
                test: /\.(jsx|tsx|js|ts)$/,
                loader: 'ts-loader',
                options: {
                    // transpileOnly: true,
                    // getCustomTransformers: () => ({
                    //     before: [tsImportPluginFactory( /** options */)]
                    // }),
                    // compilerOptions: {
                    //     module: 'es2015'
                    // }
                },
                exclude: /node_modules/
            },
            {
                test: /\.(css|scss)$/,
                exclude: /\.module\.scss$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader',
                    {
                        // 帮postcss找到package.json中browserslist里面的配置，通过配置加载指定的css兼容性样式
                        loader: 'postcss-loader',
                        options: {
                            postcssOptions: {
                                plugins: [
                                    [require('postcss-preset-env')()],
                                    postcssAspectRatioMini({}),
                                    postcssPxToViewport({
                                        viewportWidth: 750, // (Number) The width of the viewport.
                                        viewportHeight: 1334, // (Number) The height of the viewport.
                                        unitPrecision: 3, // (Number) The decimal numbers to allow the REM units to grow to.
                                        viewportUnit: 'vw', // (String) Expected units.
                                        selectorBlackList: ['.ignore', '.hairlines', '.list-row-bottom-line', '.list-row-top-line'], // (Array) The selectors to ignore and leave as px.
                                        minPixelValue: 1, // (Number) Set the minimum pixel value to replace.
                                        mediaQuery: false // (Boolean) Allow px to be converted in media queries.
                                    }),
                                    postcssWriteSvg({ utf8: false }),
                                    postcssCssnext({}),
                                    // postcssViewportUnits({
                                    //  filterRule: rule => rule.selector.indexOf('::after') === -1 && rule.selector.indexOf('::before') === -1 && rule.selector.indexOf(':after') === -1 && rule.selector.indexOf(':before') === -1
                                    // }),
                                    postcssViewportUnits({}),
                                    cssnano({
                                        "cssnano-preset-advanced": {
                                            zindex: false,
                                            autoprefixer: false
                                        },
                                    })
                                ]
                            }
                        },
                    },
                    'sass-loader'
                ],
            },
            {
                test: /\.module\.scss$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    {
                        loader: 'css-loader',
                        options: {
                            modules: {
                                getLocalIdent: getCSSModuleLocalIdent,
                            },
                        },
                    },
                    'postcss-loader', 'sass-loader'],
            },
            { test: /\.(jpe?g|png|gif|svg|woff|woff2|eot|ttf|otf)$/i, type: "asset/resource" },
        ],
    },

    // 引入了缓存来提高二次构建速度
    cache: {
        type: 'filesystem',
        // 可选配置
        buildDependencies: {
            config: [__filename], // 当构建依赖的config文件（通过 require 依赖）内容发生变化时，缓存失效
        },
        name: 'development-cache',
    },
    // 进行第三方库代码分离 - 压缩css
    optimization
}
